const tbody = document.querySelector('tbody');
const button = document.querySelector('button');
const showCommentBtn = document.querySelector('#showCommentBtn');
const dataJSON = JSON.parse(localStorage.getItem('giteefe'));
let list = [];
NProgress.start();
// if (dataJSON && Date.now() - dataJSON.time < 1000 * 60) {
//   // 使用缓存数据
//   list = dataJSON.list;
//   render();
// } else {
// }
getData();

function getData() {
  // 没有正确填写url

  data.forEach((v, i) => {
    if (!v.url.trim()) {
      list.push({ name: v.name, url: v.url, data: [] });
      return;
    }

    const [user, repos] = v.url.trim().replace('https://gitee.com/', '').split('/');
    const url = `https://gitee.com/api/v5/repos/${user}/${repos}/commits`;
    const params = {
      access_token: document.querySelector('input').value,
      page: 1,
      per_page: 100,
    };
    axios
      .get(url, { params })
      .then((result) => {
        list.push({ name: v.name, url: v.url, data: result.data });
      })
      .catch((err) => {
        list.push({ name: v.name, url: v.url, data: [] });
      })
      .finally(() => {
        if (list.length === data.length) {
          console.log(data.length, list.length);
          console.log('结束');

          localStorage.setItem(
            'giteefe',
            JSON.stringify({ time: Date.now(), list })
          );
          render();
          console.log(list.map((v) => v.name));
        }
      });
  });
}
function render() {
  NProgress.done();
  tbody.innerHTML = list
    .sort((a, b) => a.data.length - b.data.length)
    .reduce((h, v, i) => {
      return (
        h +
        `
<tr>
<td> ${i + 1} </td>
<td> ${v.name}</td>

<td>
<h4>提交记录:${v.data.length}</h4>
<ul class="list-group">
  ${v.data.reduce(
          (hh, vv, ii) =>
            hh +
            `    <li class="list-group-item" >${vv.commit.message} --  ${new Date(
              vv.commit.committer.date
            ).toLocaleString()}</li>`,
          ''
        )}
</ul>
</td>
<td> <a href="${v.url}" target="_blank"  class="btn btn-default">${v.url}</a> </td>
</tr>
`
      );
    }, '');
}
showCommentBtn.addEventListener('click', function () {
  document
    .querySelectorAll('.ttbody .list-group ')
    .forEach((v) => v.classList.toggle('list-group'));
});

button.addEventListener('click', function () {
  localStorage.removeItem('giteefe');
  location.reload();
});

tbody.addEventListener('click', function (e) {
  console.log(e.target.nodeName);
  if (e.target.nodeName === 'H4') {
    e.target.classList.toggle('list-group');
  }
});
